﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using BCService.Common.UploadFileRecord;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;

namespace BCTMSRESTful.Controllers.Anonymous
{
    [Route("api/v1/[controller]")]
    [ApiController]
    public class OSSCallbackController : BCTMSRESTfulAPIController
    {
        private readonly IUploadFileRecordService uploadFileRecordService;

        public OSSCallbackController(IUploadFileRecordService uploadFileRecordService)
        {
            this.uploadFileRecordService = uploadFileRecordService;
        }

        #region 接收OSS上传回调
        /// <summary>
        /// 接收OSS上传回调。
        /// </summary>
        /// <response code="200">已正确接收异步通知。</response>
        /// <returns></returns>
        [AllowAnonymous]
        [HttpGet("[action]"), HttpPost("[action]")]
        public IActionResult CallbackResult()
        {
            Dictionary<string, string> dictionary = new Dictionary<string, string>();

            if (this.Request.Method == "GET")
            {
                foreach (var item in this.Request.Query)
                {
                    dictionary.Add(item.Key, item.Value);
                }
            }
            else
            {
                if (this.Request.HasFormContentType)
                {
                    foreach (var item in this.Request.Form)
                    {
                        dictionary.Add(item.Key, item.Value);
                    }
                }

                if (this.Request.ContentLength > 0 && !dictionary.Any())
                {
                    byte[] buffer = new byte[Request.ContentLength.Value];

                    this.Request.Body.Read(buffer, 0, buffer.Length);

                    dictionary.Add("Request-Body", Encoding.UTF8.GetString(buffer));
                }
            }
            string dataParameters = string.Join("\r\n", dictionary.Select(p => $"{p.Key}={p.Value}"));
            Log(dataParameters);

            if (this.uploadFileRecordService.UpdateTransported(dictionary["upload_file_record_no"].Replace("x:", "")))
            {
                return this.Json(new { Status = "OK" });
            }
            else
            {
                return this.Json(new { Status = "Field" });
            }
        }
        #endregion

        private void Log(string str)
        {
            DirectoryInfo directoryInfo = new DirectoryInfo(Directory.GetCurrentDirectory());
            string path = Path.Combine(directoryInfo.FullName, "OSSLog", DateTime.Now.ToString("yyyy-MM-dd"));
            if (!Directory.Exists(path))
            {
                Directory.CreateDirectory(path);
            }
            FileInfo fileInfo = new FileInfo(Path.Combine(path, "OSSCallbackRecord.txt").ToString());
            Console.WriteLine("*****************************************");
            Console.WriteLine(str);
            Console.WriteLine(path);
            if (!fileInfo.Exists)
            {
                using (StreamWriter sw = fileInfo.CreateText())
                {
                    sw.WriteLine("*****************************************");
                    sw.WriteLine("当前时间：{0}", DateTime.Now.ToString());
                    sw.WriteLine("{0}", str);
                }
            }
            else
            {
                using (StreamWriter sw = fileInfo.AppendText())
                {
                    sw.WriteLine("*****************************************");
                    sw.WriteLine("当前时间：{0}", DateTime.Now.ToString());
                    sw.WriteLine("{0}", str);
                }
            }
        }
    }

}
